package com.douwong.student.activity;

import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.douwong.student.R;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseActivity;
import com.douwong.student.contant.NetConfig;
import com.douwong.student.model.NoticeObj;
import com.douwong.student.model.PrepareBean;
import com.douwong.student.model.StatusCode;
import com.douwong.student.utils.CyptoUtils;
import com.douwong.student.utils.NetUtils;

import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @autor yichao
 * @time 2017/3/299:54
 * @des 通知
 */
public class NoticActivity  extends BaseActivity {
    ListView notice_list;
    private NoticeAdapter adapter;
    private ArrayList<NoticeObj> list;
    private String TAG="NoticeActivity";
    @Override
    protected void initView() {
        setContentView(R.layout.notice_layout);
        notice_list=(ListView)findViewById(R.id.notice_list);
        list=new ArrayList<NoticeObj>();
        adapter=new NoticeAdapter();
        notice_list.setAdapter(adapter);
        getNoticeList();
        findViewById(R.id.go_back_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                setResult(MainActivity.NoticeResponeCode);
                finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
         setResult(MainActivity.NoticeResponeCode);

        }

        return super.onKeyDown(keyCode, event);
    }

    private void getNoticeList(){

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    List<BasicNameValuePair> ps = new ArrayList<BasicNameValuePair>();
                    ps.add(new BasicNameValuePair("object", "3"));
                    if( BaseApplication.sUserBean.getClassbean()!=null){
                        ps.add(new BasicNameValuePair("objectId", BaseApplication.sUserBean.getClassbean().getId()+""));
                    }else{
                        return;
                    }
                    String result= NetUtils.httpGet(NetConfig.NOTICE_LIST, ps);
                    if(result!=null){
                        StatusCode<PrepareBean> sc = (StatusCode<PrepareBean>) JSON.parseObject(result,
                                new TypeReference<StatusCode<PrepareBean>>()
                                {
                                });
                        if (sc != null && sc.isFlag()) {
                            ArrayList<NoticeObj> notices = (ArrayList<NoticeObj>) JSON.parseArray(sc.getData().getRows(),
                                    NoticeObj.class);
                            if (notices != null && notices.size() > 0) {
                                list.addAll(notices);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        adapter.notifyDataSetChanged();
                                    }
                                });

                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }
    private class NoticeAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder=null;
            if(convertView==null){
                holder=new Holder();
                convertView= LayoutInflater.from(NoticActivity.this).inflate(R.layout.notice_item, null);
                holder.notice_type=(TextView) convertView.findViewById(R.id.notice_type);
                holder.notice_time=(TextView) convertView.findViewById(R.id.notice_time);
                holder.notice_content=(TextView) convertView.findViewById(R.id.notice_content);
                convertView.setTag(holder);
            }else{
                holder=(Holder) convertView.getTag();
            }
            try {
                if(list.size()>0){
                    holder.notice_type.setText(list.get(position).getHaTitle());
                    holder.notice_time.setText(list.get(position).getCreatetime());
                    holder.notice_content.setMovementMethod(LinkMovementMethod.getInstance());
                    String formatContent=handleHtmlStr(list.get(position).getHaContent().trim());
                    holder.notice_content.setText(getClickableHtml(formatContent));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return convertView;
        }
        public class Holder {
            TextView notice_type,notice_time,notice_content;
        }

    }

    private String handleHtmlStr(String html){
        try {
            if(html.contains("microclassdetail")){

                String useKey=BaseApplication.sUserBean.getUserbean().getEuNumber()+"|"+ CyptoUtils.MD5("123456");
                //	String pageUrl="href=http://www.eclassedu.com/edu/index/login.html?pageCode=9";
                //String pageUrl="href=http://xiaodou.eclassedu.com/edu/index/login.html?pageCode=9";
                String pageUrl="href=http://edu.douwong.com/edu/index/login.html?pageCode=9";

                String microId=null;
                Pattern pattern=Pattern.compile("href=\"(.+?)\"");
                Matcher matcher=pattern.matcher(html);
                while(matcher.find()){
                    String tag=matcher.group();
                    microId=tag.substring(tag.lastIndexOf("/")+1, tag.lastIndexOf("."));
                    StringBuilder sBuilder=new StringBuilder();
                    sBuilder.append(pageUrl);
                    sBuilder.append("&microid=");
                    sBuilder.append(microId);
                    sBuilder.append("&key=");
                    sBuilder.append(Base64.encodeToString(useKey.getBytes("utf-8"),Base64.DEFAULT));
                    html=matcher.replaceFirst(sBuilder.toString());
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return html.trim();
    }

    private void setLinkClickable(final SpannableStringBuilder clickableHtmlBuilder,
                                  final URLSpan urlSpan) {
        int start = clickableHtmlBuilder.getSpanStart(urlSpan);
        int end = clickableHtmlBuilder.getSpanEnd(urlSpan);
        int flags = clickableHtmlBuilder.getSpanFlags(urlSpan);
        ClickableSpan clickableSpan = new ClickableSpan() {
            public void onClick(View view) {
                //				//Do something with URL here.
                //				Log.d(TAG,"xxxxxxxxxxxxxxxxxxxxxxxxxx");
                Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(urlSpan.getURL()));
                Log.i(TAG,"NoticActivity: 跳转的路径 ："+urlSpan.getURL());
                it.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
                try {
                    NoticActivity.this.startActivity(it);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        };
        clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags);
    }
    private CharSequence getClickableHtml(String html) {
        Spanned spannedHtml = Html.fromHtml(html);
        SpannableStringBuilder clickableHtmlBuilder = new SpannableStringBuilder(spannedHtml);
        URLSpan[] urls = clickableHtmlBuilder.getSpans(0, spannedHtml.length(), URLSpan.class);
        for(final URLSpan span : urls) {
            //			Log.d(TAG,"url : "+span.getURL());
            setLinkClickable(clickableHtmlBuilder, span);
        }
        return clickableHtmlBuilder;
    }

}
